// miniprogram/pages/homemate/homemate.js
import Toast from '@vant/weapp/toast/toast';
import {
  wxp
}
from '../../../util/wxp'
const db = wx.cloud.database()

Page({
  mixins: [require('../../../mixins/pageMixins')],
  /**
   * 页面的初始数据
   */
  data: {
    columns: ['夫妻', '父母', '子女', '亲朋好友', '其他'],
    form: {
      name: null,
      age: null,
      longLive: true,
      relation: null,
      _id: null
    }
  },
  async onLoad(options) {
    // 加载数据
    if (options._id) {
      const {
        data
      } = await db.collection('homemate').doc(options._id).get()
      delete data._openid
      this.setData({
        form: data
      })
    }
  },
  onRelateChange(e) {
    this.setData({
      'form.relation': e.detail.value
    })
    this.closePopup()
  },
  getPrevPage() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; //上一个页面     
    return prevPage
  },
  async deleteInfo() {
    await db.collection('homemate').doc(this.data.form._id).update({
      data: {
        deleted: 1,
        updateTime: db.serverDate()
      }
    })
    // 删除数据
    db.collection('record').where({
      homemate: this.data.form._id
    }).update({
      data: {
        deleted: 1,
        updateData: db.serverDate()
      }
    })
    this.getPrevPage().updateData()
    wx.navigateBack()
  },
  async saveInfo() {
    if (!this.data.form.name) {
      Toast('请输入姓名');
      return
    }
    const {
      _id
    } = this.data.form
    if (_id) {
      delete this.data.form._id
      this.data.form.updateTime = db.serverDate()
      await db.collection('homemate').doc(_id).update({
        data: this.data.form
      })
    } else {
      this.data.form.addTime = db.serverDate()
      await db.collection('homemate').add({
        data: this.data.form
      })
    }

    this.getPrevPage().updateData()
    wx.navigateBack()
  }
})